package org.ajax.util;

import java.sql.*;

/*
 *
 *@author XCH
 *@date2024 - 10 - 09
 *
 */
public class DbUtil {
    // 定义数据库连接URL
    private static final String URL = "jdbc:sqlserver://localhost:1433;database=Users;encrypt=true;trustServerCertificate=true;";

    // 定义数据库驱动类
    private static final String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

    // 定义数据库用户
    private static final String username = "sa";

    // 定义数据库密码
    private static final String password = "root";

    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(URL, username, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /*
    * 关闭数据库资源
    *
    * @param rst 结果集 - 用于储存查询结果
    * @param stmt 语句对象 - 用于执行sql语句
    * @param conn 连接对象 - 用于连接数据库
    */
    public static void close(ResultSet rst, Statement stmt, Connection conn){
        // 关闭结果集对象，释放资源
        if(rst != null){
            try {
                rst.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        // 关闭语句对象，释放资源
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        // 关闭数据库连接对象，释放资源
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
